package org.javaymw.springboot.base;

import com.github.pagehelper.PageHelper;

import org.apache.shiro.SecurityUtils;
import org.javaymw.springboot.base.constant.Constants;
import org.javaymw.springboot.base.session.SessionProvider;
import org.javaymw.springboot.dto.UserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * 描述：
 * <p>
 * Author: 赵新国
 * Date: 2017/10/25 11:41
 */
public abstract class BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected SessionProvider sessionProvider;

    @Autowired
    protected ApplicationEventPublisher eventPublisher;

    @Autowired
    protected CacheManager cacheManager;

    @Autowired
    protected RedisTemplate redisTemplate;

    protected String getSessionId(HttpServletRequest request) {
        return sessionProvider.getSessionId(request);
    }

    protected Serializable getAttribute(HttpServletRequest request, String name) {
        return sessionProvider.getAttribute(request, name);
    }

    /**
     * 左侧菜单缓存
     * @return
     */
    protected Cache getLeftMenuTreeCacheName() {
        return cacheManager.getCache("LeftMenuTreeCache");
    }

    protected Long getId() {
        UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute(Constants.ADMIN_SESSION);
        if (userDto != null) {
            return userDto.getId();
        }
        return 0L;
    }

    public static HttpServletRequest getRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 开启分页
     */
    protected void startPage() {
        int pageNumber = 1;//页号 默认1
        int pageSize = 10;//每页数据条数 默认10条
        if (getRequest().getParameter("pageNumber") != null) {
            pageNumber = Integer.parseInt(getRequest().getParameter("pageNumber"));
        }
        if (getRequest().getParameter("pageSize") != null) {
            pageSize = Integer.parseInt(getRequest().getParameter("pageSize"));
        }
        PageHelper.startPage(pageNumber, pageSize);
    }

}
